package com.topone.permission.utils;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContextHolder;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.topone.permission.model.UserSeesion;
import com.topone.permission.result.Result;

public class ControllerUtils {
	
	public static UserSeesion getUser(){
		UserSeesion session = (UserSeesion) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
		return session;
	}
	
	public static void failedRepose(HttpServletRequest request, HttpServletResponse response,Exception exception) throws IOException{
		ObjectMapper om=new ObjectMapper ();
		PrintWriter writer = response.getWriter();
		writer.write(om.writeValueAsString(Result.error("5000",exception.getMessage())));
		writer.flush();
	}
	
	public static void failedRepose(HttpServletRequest request, HttpServletResponse response,String code,String message) throws IOException{
		ObjectMapper om=new ObjectMapper ();
		PrintWriter writer = response.getWriter();
		writer.write(om.writeValueAsString(Result.error(code,message)));
		writer.flush();
	}

	public static void SuccessfulRepose(HttpServletRequest request, HttpServletResponse response,Object object) throws IOException{
		ObjectMapper om=new ObjectMapper ();
		PrintWriter writer = response.getWriter();
		writer.write(om.writeValueAsString(object));
		writer.flush();
	}
	
}
